package com.lu.study.lu.api.response;

import com.lu.study.lu.base.framework.exception.ApiErrorCode;
import com.lu.study.lu.base.framework.exception.ApiException;
import com.lu.study.lu.base.framework.exception.IErrorCode;
import lombok.Data;

import java.util.Optional;

@Data
public class ResponseBody<T> {

    /**
     * 业务成功与否
     */
    private Long code;


    /**
     * 成功的结果集
     */
    private T data;

    /**
     * 结果描述
     */
    private String msg;

    public ResponseBody() {
        // to do nothing
    }

    public ResponseBody(IErrorCode errorCode) {
        errorCode = Optional.ofNullable(errorCode).orElse(ApiErrorCode.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public static <T> ResponseBody<T> ok(T data) {
        return restResult(data, ApiErrorCode.SUCCESS);
    }

    public static <T> ResponseBody<T> failed(String msg) {
        return restResult(null, ApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> ResponseBody<T> failed(IErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> ResponseBody<T> restResult(T data, IErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> ResponseBody<T> restResult(T data, long code, String msg) {
        ResponseBody<T> apiResult = new ResponseBody<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public boolean ok() {
        return ApiErrorCode.SUCCESS.getCode() == code;
    }

    /**
     * 服务间调用非业务正常，异常直接释放
     */
    public T serviceData() {
        if (!ok()) {
            throw new ApiException(this.msg);
        }
        return data;
    }

}
